package com.hjy.web;

import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;

@Controller
public class HelloController {

    @RequestMapping("/hello1")
    @ResponseBody
    public String test(Model model) throws IOException {
        Configuration configuration = new Configuration(Configuration.VERSION_2_3_22);
        configuration.setEncoding(Locale.CHINESE,"UTF-8");
        System.out.println(Thread.currentThread().getContextClassLoader().getResource("").getPath());
        configuration.setDirectoryForTemplateLoading(new File(Thread.currentThread().getContextClassLoader().getResource("").getPath() + "templates/"));

        HashMap<String, Object> map = new HashMap<>();
        map.put("name","hjy");
        map.put("class","527班");
        map.put("time",new Date());

        File dir = new File("C:\\Users\\hjy\\Desktop");
        if (!dir.exists()) {
            dir.mkdirs();
        }

        File file = new File(dir, "heh.docx");
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream(file), Charset.defaultCharset());
        Template template = configuration.getTemplate("test.ftl");
        try {
            template.process(map,outputStreamWriter);
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            outputStreamWriter.flush();
            outputStreamWriter.close();
        }

        return "生成完毕";
    }

    @RequestMapping("/hello2")
    @ResponseBody
    public String test2() {
        return "test";
    }
}
